package com.humanresource.action.clerkrecord;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.humanresource.constant.Constant;
import com.humanresource.domain.Result;
import com.humanresource.domain.po.clerkrecord.Clerkbaseinfo;
import com.humanresource.domain.po.clerkrecord.Clerkdetailinfo;
import com.humanresource.domain.po.clerkrecord.ClerkdetailinfoWithBLOBs;
import com.humanresource.domain.po.clerkrecord.Clerkinstpos;
import com.humanresource.domain.po.clerkrecord.Clerkrecords;
import com.humanresource.domain.po.clerkrecord.Inst;
import com.humanresource.domain.po.clerksalary.Clerkrewardpunishstandard;
import com.humanresource.domain.po.clerksalary.Possalarystandard;
import com.humanresource.domain.po.clerksalary.Salarystandard;
import com.humanresource.domain.vo.clerkrecord.RecordBaseInfoVO;
import com.humanresource.domain.vo.clerkrecord.RecordInfoVO;
import com.humanresource.service.clerkrecord.ClerkBaseInfoService;
import com.humanresource.service.clerkrecord.ClerkDetailInfoService;
import com.humanresource.service.clerkrecord.ClerkRecordService;
import com.humanresource.service.clerkrecord.InstService;
import com.humanresource.service.clerkrecord.PosService;
import com.humanresource.service.clerksalary.SalarystandardService;
import com.humanresource.utils.DateUtil;
import com.humanresource.utils.RandomUtils;
import com.humanresource.utils.ResultUtil;

@Controller
@RequestMapping("/record")
public class ClerkRecordController {

	@Autowired
	private ClerkRecordService clerkRecordService;

	@Autowired
	private ClerkBaseInfoService clerkBaseInfoService;

	@Autowired
	private ClerkDetailInfoService clerkDetailInfoService;

	@Autowired
	private InstService instService;

	@Autowired
	private PosService posService;

	@Autowired
	private SalarystandardService salarystandardService;

	/**
	 * 登记员工档案信息
	 * 1.2.1	人力资源档案登记
	 * @param recordInfoVO
	 * @return
	 */
	@RequestMapping(value = "/insert/record", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result insert(@RequestBody RecordInfoVO recordInfoVO,
			HttpServletRequest request) {
		request.getSession().setAttribute("clerkname",
				recordInfoVO.getClerkname());

		System.out.println("clerkname姓名："
				+ request.getSession().getAttribute("clerkname"));

		/**
		 * 生成员工编号
		 */
		Integer clerkid = Integer.parseInt(RandomUtils.generateNum(9));

		/**
		 * 创建员工基本信息clerkbaseinfo
		 */
		Clerkbaseinfo clerkbaseinfo = new Clerkbaseinfo();

		/**
		 *  将页面上的员工基本信息封装到clerkbaseinfo中
		 */
		BeanUtils.copyProperties(recordInfoVO, clerkbaseinfo);

		/**
		 *  员工的默认密码为其用户名
		 */
		clerkbaseinfo.setClerkpassword("123456");

		/**
		 * 设置员工编号
		 */
		clerkbaseinfo.setClerkid(clerkid);

		/**
		 *  添加员工
		 */
		clerkBaseInfoService.insert(clerkbaseinfo);

		/**
		 *  创建员工详细信息
		 */
		ClerkdetailinfoWithBLOBs clerkdetailinfoWithBLOBs = new ClerkdetailinfoWithBLOBs();

		/**
		 *  将页面的详细员工信息封装到员工详细java对象中
		 */
		BeanUtils.copyProperties(recordInfoVO, clerkdetailinfoWithBLOBs);

		/**
		 *  设置员工编号
		 */
		clerkdetailinfoWithBLOBs.setClerkid(clerkid);

		/**
		 * 添加员工详细信息
		 */
		clerkDetailInfoService.insert(clerkdetailinfoWithBLOBs);

		/**
		 *  关联用户与机构和职位
		 */
		Integer instId = instService.findByName(recordInfoVO.getInstname())
				.getInstid();// 获得机构编号
		Integer posId = posService.findByName(recordInfoVO.getPosname())
				.getPosid();// 获得职位编号
		Clerkinstpos clerkinstpos = new Clerkinstpos();
		clerkinstpos.setClerkid(clerkid);// 设置职工编号
		clerkinstpos.setInstid(instId);// 设置机构编号
		clerkinstpos.setPosid(posId);// 设置职位编号

		/**
		 * 设置员工的所在机构以及职位信息
		 */
		clerkBaseInfoService.addPosToClerk(clerkinstpos);

		/**
		 *  添加该用户的奖惩情况为“无功无过”
		 */
		Clerkrewardpunishstandard clerkrewardpunishstandard = new Clerkrewardpunishstandard();
		clerkrewardpunishstandard.setClerkid(clerkid);// 设置职工编号
		clerkrewardpunishstandard.setRewardpunishmentstandardid("5000E000");// 设置奖惩标准，初始化为“无功无过”的奖惩标准
		this.clerkBaseInfoService
				.setClerkrewardpunishstandard(clerkrewardpunishstandard);// 设置新添员工的奖惩标准

		/**
		 *  保存员工档案信息
		 */
		Clerkrecords clerkrecords = new Clerkrecords();
		// 档案编号组成：年份（4位）+一级结构编号（2位）+二级机构编号（2位）+三级机构编号（2位）+编号（2位）
		Integer inst2Id = instService.findPById(instId).getInstid();
		Integer inst3Id = instService.findPById(inst2Id).getInstid();

		/**
		 * 生成员工档案编号
		 */
		String recordId = DateUtil.getYear(new Date()) + ""
				+ (instId > 9 ? instId : 0 + "" + instId)
				+ (inst2Id > 9 ? inst2Id : 0 + "" + inst2Id)
				+ (inst3Id > 9 ? inst3Id : 0 + "" + inst3Id)
				+ RandomUtils.generateString(2);

		/**
		 * 登记人的职工编号
		 */
		Integer bookerId = clerkBaseInfoService.findByName(
				recordInfoVO.getBookername()).getClerkid();

		/**
		 *  档案生成时间
		 */
		String createTime = DateUtil.formatDateByFormat(new Date(),
				DateUtil.DATETIME_FORMAT);
		/**
		 *  设置档案编号
		 */
		clerkrecords.setRecordsid(recordId);
		/**
		 *  设置员工编号
		 */
		clerkrecords.setClerkid(clerkid);
		/**
		 *  设置登记人编号
		 */
		clerkrecords.setBookerid(bookerId);
		/**
		 *  设置创建时间
		 */
		clerkrecords.setCreatetime(createTime);
		/**
		 *  设置为待复核状态
		 */
		clerkrecords.setAuditstate(Constant.CLERKNOCHECK);
		/**
		 *  设置为存在状态，表示该职工不是被删除的职工
		 */
		clerkrecords.setIsdelete(Constant.CLERKEXIT);
		/**
		 *  添加职工档案信息
		 */
		clerkRecordService.insert(clerkrecords);

		/**
		 * 根据员工所在机构生成薪酬发放单或更改薪酬发放单
		 */
		this.salarystandardService.createOrupdateSalarydistribution(
				recordInfoVO.getInstname(), recordInfoVO.getPosname());

		/**
		 * 初始化生成该员工的薪酬发放详细信息
		 */
		// 根据职位获得薪酬标准
		Salarystandard salarystandard = this.salarystandardService
				.findById(this.posService.findByPosId(posId)
						.getSalarystandardid());
		this.salarystandardService.createSalarydistributiondetail(recordId,
				clerkid, recordInfoVO.getInstname(), salarystandard);

		return ResultUtil.success();
	}

	/**
	 * 通过档案表基本信息列表
	 * @param clerkrecordsList<Clerkrecords>
	 * @return List<RecordBaseInfoVO>
	 */
	public List<RecordBaseInfoVO> findByclerkrecordsList(
			List<Clerkrecords> clerkrecords) {
		/**
		 *  显示在页面上的员工档案基本信息
		 */
		List<RecordBaseInfoVO> recordBaseInfoVOs = new ArrayList<RecordBaseInfoVO>();

		/**
		 *  封装每一个员工的基本档案信息显示到页面上
		 */
		for (Clerkrecords clerkrecord : clerkrecords) {
			RecordBaseInfoVO recordBaseInfoVO = new RecordBaseInfoVO();
			recordBaseInfoVO.setRecordsid(clerkrecord.getRecordsid());
			// 通过员工编号获得员工基本信息
			Clerkbaseinfo clerkbaseinfo = this.clerkBaseInfoService
					.findById(clerkrecord.getClerkid());
			recordBaseInfoVO.setClerkname(clerkbaseinfo.getClerkname());
			recordBaseInfoVO.setClerksex(clerkbaseinfo.getClerksex());
			// 根据员工编号获得员工的职位和机构
			Clerkinstpos clerkinstpos = this.clerkBaseInfoService
					.findByClerkId(clerkbaseinfo.getClerkid());
			// 获得三级机构
			Inst inst3 = this.instService.findById(clerkinstpos.getInstid());
			// 获得二级机构
			Inst inst2 = this.instService.findPById(inst3.getInstid());
			// 获得一级机构
			Inst inst1 = this.instService.findPById(inst2.getInstid());
			recordBaseInfoVO.setFirstinstname(inst1.getInstname());
			recordBaseInfoVO.setSecondinstname(inst2.getInstname());
			recordBaseInfoVO.setThirdinstname(inst3.getInstname());

			// 封装职位名称
			recordBaseInfoVO.setPosname(this.posService.findById(
					clerkinstpos.getPosid()).getPosname());
			recordBaseInfoVOs.add(recordBaseInfoVO);
		}
		return recordBaseInfoVOs;
	}

	/**
	 * 待复核的员工档案基本信息
	 * 1.2.2	人力资源档案登记复核
	 * 如果data为null，则不存在待复核员工
	 * 反之则存在待复核员工
	 * @return
	 */
	@RequestMapping(value = "/record/withoutcheck", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result RecordsWithoutCheck() {
		// 获得员工档案信息表
		List<Clerkrecords> clerkrecords = this.clerkRecordService
				.findwithoutcheck();
		// 如果不存在待复核的员工信息，则返回成功，但data为空
		if (clerkrecords.size() == 0) {
			return ResultUtil.success();
		}
		List<RecordBaseInfoVO> recordBaseInfoVOs = findByclerkrecordsList(clerkrecords);
		Integer size = clerkrecords.size();// 记录数
		return ResultUtil.success(recordBaseInfoVOs, size + "");
	}

	/**
	 * 根据档案编号获取详细信息
	 * 1.2.2	人力资源档案登记复核时查询该员工的档案信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/record/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result getOne(@PathVariable(value = "id") String id) {
		RecordInfoVO recordInfoVO = new RecordInfoVO();

		// 根据clerkrecordsId获取档案信息
		Clerkrecords clerkrecords = this.clerkRecordService.findById(id);

		// 根据clerkId获取员工基本信息
		Clerkbaseinfo clerkbaseinfo = this.clerkBaseInfoService
				.findById(clerkrecords.getClerkid());

		// 根据clerkId获取员工详细信息
		Clerkdetailinfo clerkdetailinfo = this.clerkDetailInfoService
				.findByClerkId(clerkrecords.getClerkid());

		// 根据clerkId获取该员工的职位信息与机构信息
		Clerkinstpos clerkinstpos = this.clerkBaseInfoService
				.findByClerkId(clerkrecords.getClerkid());

		// 根据职位获取该员工的薪酬标准
		Possalarystandard possalarystandard = this.posService
				.findByPosId(clerkinstpos.getPosid());

		BeanUtils.copyProperties(clerkdetailinfo, recordInfoVO);
		// 档案编号
		recordInfoVO.setRecordsid(clerkrecords.getRecordsid());
		// 设置员工状态
		recordInfoVO.setAuditstate(clerkrecords.getAuditstate());
		// 员工姓名
		recordInfoVO.setClerkname(clerkbaseinfo.getClerkname());
		// 设置头像路径
		recordInfoVO.setClerkphotopath(clerkbaseinfo.getClerkphotopath());
		// 设置性别
		recordInfoVO.setClerksex(clerkbaseinfo.getClerksex());
		// 登记人姓名
		recordInfoVO.setBookername(clerkBaseInfoService.findById(
				clerkrecords.getBookerid()).getClerkname());
		// 员工姓名
		recordInfoVO.setInstname(this.instService.findById(
				clerkinstpos.getInstid()).getInstname());
		// 职称
		recordInfoVO.setPosname(this.posService.findById(
				clerkinstpos.getPosid()).getPosname());
		// 薪酬标准
		recordInfoVO.setSalarystandardname(this.salarystandardService.findById(
				possalarystandard.getSalarystandardid())
				.getSalarystandardname());
		// 查询员工基本信息
		return ResultUtil.success(recordInfoVO);
	}

	/**
	 * 员工档案信息复核后提交进行修改
	 * 1.2.2	人力资源档案登记复核
	 * 1.2.4	人力资源档案变更
	 * @param recordInfoVO
	 * @return
	 */
	@RequestMapping(value = "/record/update", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result updateClerkRecord(@RequestBody RecordInfoVO recordInfoVO) {

		/**
		 * 修改员工档案信息表
		 */
		Clerkrecords clerkrecords = new Clerkrecords();
		// 根据员工名设置员工档案编号
		clerkrecords.setRecordsid(this.clerkRecordService.findByClerkId(
				this.clerkBaseInfoService.findByName(
						recordInfoVO.getClerkname()).getClerkid())
				.getRecordsid());

		// 如果是变更操作，要将该档案的状态从新设置为待复核//////////////////////////////////////////////////////////////////////
		if (recordInfoVO.getUpdatename() != null) {
			// 设置变更人编号
			clerkrecords.setUpdaterid(this.clerkBaseInfoService.findByName(
					recordInfoVO.getUpdatename()).getClerkid());
			// 设置变更时间
			clerkrecords.setUpdatetime(DateUtil.formatDateByFormat(new Date(),
					DateUtil.DATETIME_FORMAT));
			clerkrecords.setAuditstate("待复核");
		} else {// 如果是复核执行以下操作
			// 更改员工档案的复核状态为“正常”
			clerkrecords.setAuditstate("正常");
			// 通过复核人姓名设置复核人编号
			clerkrecords.setCheckerid(this.clerkBaseInfoService.findByName(
					recordInfoVO.getCheckername()).getClerkid());
			// 设置复核时间
			clerkrecords.setChecktime(DateUtil.formatDateByFormat(new Date(),
					DateUtil.DATETIME_FORMAT));

		}
		// ///////////////////////////////////////////////////////////////////////////////////////////////////////////

		this.clerkRecordService.update(clerkrecords);

		/**
		 * 修改员工详细信息表
		 */
		ClerkdetailinfoWithBLOBs clerkdetailinfoWithBLOBs = new ClerkdetailinfoWithBLOBs();
		BeanUtils.copyProperties(recordInfoVO, clerkdetailinfoWithBLOBs);
		// 设置员工编号
		clerkdetailinfoWithBLOBs.setClerkid(this.clerkBaseInfoService
				.findByName(recordInfoVO.getClerkname()).getClerkid());
		this.clerkDetailInfoService.update(clerkdetailinfoWithBLOBs);

		return ResultUtil.success();
	}

	/**
	 * 按条件查询
	 * 查询条件包括：员工所在机构，职位和建档时间。
	 * 1.2.3	人力资源档案查询
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "/record/query", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result clerkrecordlist(HttpServletRequest request) {
		// 通过员工所在机构，职位和建档时间查询所有员工档案信息
		String thirdinstname = request.getParameter("thirdinstname");
		String posname = request.getParameter("posname");
		String starttime = request.getParameter("starttime");
		String endtime = request.getParameter("endtime");
		List<Clerkrecords> clerkrecordsList = this.clerkBaseInfoService
				.findBy3instname2posnameandcretetime(thirdinstname, posname,
						starttime, endtime);
		if (clerkrecordsList == null) {
			return ResultUtil.success();
		}
		List<RecordBaseInfoVO> recordBaseInfoVOs = findByclerkrecordsList(clerkrecordsList);
		return ResultUtil.success(recordBaseInfoVOs, clerkrecordsList.size()
				+ "");
	}

	/**
	 * 1.2.5	人力资源档案删除管理
	 * 标记想要删除的记录状态为“已删除”。 
	 * 状态为“待复核”的员工档案不能删除。
	 * 状态为“已删除”的人资档案还可以恢复。
	 * @param clerkrecords
	 * @return
	 */
	@RequestMapping(value = "/record/delete", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result delete(@RequestBody Clerkrecords clerkrecords) {
		// 查询该员工的状态
		Clerkrecords clerkrecords2 = this.clerkRecordService
				.findById(clerkrecords.getRecordsid());
		if (clerkrecords2.getAuditstate().equals(Constant.CLERKNOCHECK)) {
			return ResultUtil.error(100, "删除失败");
		}
		// 将该员工的档案信息的删除状态设置为“删除”
		clerkrecords.setAuditstate(Constant.DELETE);
		clerkrecords.setIsdelete(Constant.DELETE);
		this.clerkRecordService.update(clerkrecords);
		return ResultUtil.success();
	}

}
